#!/usr/bin/env python
# coding:utf-8

def asset_day(date1,date2,todo):
    todo=set(todo)
    for t in todo:
        if t not in ('money','score','gamecoin','charm'):
            todo.remove(t)
    if len(todo)<=0:
        return
    import common.db
    bill_connection = common.db.connect('billDB')
    bill_cursor = bill_connection.cursor()

    import logging
    date_line1=date1.isoformat()
    date_line2=date2.isoformat()
    sql_format="delete from statisticdb_dmz.%%s where date between '%s' and '%s'"%(date_line1,date_line2)
    for t in todo:
        num=bill_cursor.execute(sql_format%t)
        logging.log(logging.INFO,'delete %s %s~%s: %d'%(t,date_line1,date_line2,num))

    sql_format='''
insert into statisticdb_dmz.%s
select '%%s',ZoneID,substring(TransID,locate('TP',TransID)+2,2) ServerID,ChannelID,
sum(%s),count(RoleID),count(distinct RoleID)
from dmz_bill_%%s.%s
group by ZoneID,ServerID,ChannelID,%s
    '''
    sql={}
    sql['money']=sql_format%('money','MoneyNew-MoneyOld','money','MoneyNew>MoneyOld')
    sql['score']=sql_format%('score','MoneyNew-MoneyOld','score','MoneyNew>MoneyOld')
    sql['gamecoin']=sql_format%('gamecoin','GameCoinNew-GameCoinOld','gamecoin','GameCoinNew>GameCoinOld')
    sql['charm']=sql_format%('charm','GameCoinNew-GameCoinOld','charm','GameCoinNew>GameCoinOld')

    one_day=datetime.timedelta(days=1)
    date=date1
    while date<=date2:
        date_line=date.isoformat()
        date_number=date.strftime('%Y%m%d')

        for t in todo:
            num=bill_cursor.execute(sql[t]%(date_line,date_number))
            logging.log(logging.INFO,'insert %s %s: %d'%(t,date_line,num))
        date+=one_day

    bill_connection.commit()
    bill_cursor.close()
    bill_connection.close()

def arg_exit(tip=''):
    usage='usage:\n\tpython %s %s  [money,score,gamecoin,charm] [Y-m-d | Y-m-d~Y-m-d]' % (sys.argv[0],sys.argv[1])
    sys.exit(tip+'\n'+usage)

if __name__ != "__main__":
    import sys
    argc=len(sys.argv)
    if argc!=3 and argc!=4:
        arg_exit('argument count error')

    todo=set()
    for t in sys.argv[2].split(','):
        if t in ('money','score','gamecoin','charm'):
            todo.add(t)
        else:
            arg_exit('invalid type argument:"%s"'%t)

    import datetime
    if argc==3:
        date1=date2=datetime.date.today()-datetime.timedelta(days=1)
    else:
        count=sys.argv[3].count('~')
        import time
        try:
            if count==0:
                date1=date2=datetime.date(*time.strptime(sys.argv[3],'%Y-%m-%d')[0:3])
            elif count==1:
                date1,date2=sys.argv[3].split('~')
                date1=datetime.date(*time.strptime(date1,'%Y-%m-%d')[0:3])
                date2=datetime.date(*time.strptime(date2,'%Y-%m-%d')[0:3])
            else:
                raise ValueError('should contain at most one "~"')
        except ValueError,msg:
            arg_exit('invalid argument value "'+sys.argv[3]+'":\n\t'+str(msg))

    asset_day(date1,date2,todo)


